package com.glwan.fixedassetapp.ui.home.Activity;

import static com.glwan.fixedassetapp.utils.OffsetAssetUtils.getAssetListDataNew;
import static com.glwan.fixedassetapp.utils.OffsetAssetUtils.getTotalCount;

import android.app.Activity;
import android.app.Dialog;
import android.database.Cursor;
import android.os.Bundle;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

import com.glwan.fixedassetapp.Adapter.OfflineAdapter;
import com.glwan.fixedassetapp.R;
import com.glwan.fixedassetapp.common.DatabaseConstant;
import com.glwan.fixedassetapp.components.ConditionSearchView;
import com.glwan.fixedassetapp.components.ScrollPageView;
import com.glwan.fixedassetapp.model.Asset;
import com.glwan.fixedassetapp.utils.CommonUtil;
import com.glwan.fixedassetapp.utils.DatabaseUtil;

import java.util.ArrayList;
import java.util.List;

public class OfflineProductActivity extends AppCompatActivity {

    Dialog dialog;
    ConditionSearchView conditionSearchView;
    ScrollPageView scrollPageView;
    LinearLayout notCountedCountLinearLayout;
    LinearLayout countedCountLinearLayout;
    LinearLayout errorCountedCountLinearLayout;
    private List<Asset> parentList = new ArrayList<>();
    private ListView listView;
    private OfflineAdapter listableAdapter;
    private boolean initStatus = true;

    @Override
    protected void onCreate(@Nullable @org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fragment_home_product);
        setTitle(getString(R.string.product_list));

        Toolbar toolbar = findViewById(R.id.moreToolbar);
        setSupportActionBar(toolbar);

        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setHomeButtonEnabled(true);
            actionBar.setDisplayHomeAsUpEnabled(true);
        }

        initData();
    }


    private void initQueryButton() {
        notCountedCountLinearLayout = findViewById(R.id.notCountedCountLinearLayout);
        countedCountLinearLayout = findViewById(R.id.countedCountLinearLayout);
        errorCountedCountLinearLayout = findViewById(R.id.errorCountedCountLinearLayout);

        notCountedCountLinearLayout.setOnClickListener(view -> {
            setQueryStatus(0);
        });
        countedCountLinearLayout.setOnClickListener(view -> {
            setQueryStatus(4);

        });
        errorCountedCountLinearLayout.setOnClickListener(view -> {
            setQueryStatus(5);

        });
    }

    private void initData() {
        listView = findViewById(R.id.listView);
        listableAdapter = new OfflineAdapter(getActivity());
        listView.setAdapter(listableAdapter);

//        //长按手动更新资产盘点状态
//        listView.setOnItemLongClickListener((adapterView, view, i, l) -> {
//            new AlertDialog.Builder(getActivity()).setIcon(R.drawable.more_function).setTitle("更多").setItems(new String[]{"标签定位", "更新盘点状态"}, (dialog, which) -> {
//                Asset item = listableAdapter.getItem(i);
//                String fdId = item.getId();
//
//                if (which == 0) {
//                    Map<String, Object> map = new HashMap<>();
//                    map.put("tagPatternValue", fdId);
//                    CommonUtil.startActivity(getApplicationContext(), LocateTagActivity.class, map, true);
//                } else if (which == 1) {
//                    LayoutInflater factory = LayoutInflater.from(getActivity());
//                    View textEntryView = factory.inflate(R.layout.product_modify_dialog, null);
//                    RadioGroup radioGroup = textEntryView.findViewById(R.id.radio_group);
//                    String status = item.getInventoryStatus();
//                    if ("待盘点".equals(status)) {
//                        radioGroup.check(R.id.radio_button1);
//                    } else if ("已盘点".equals(status)) {
//                        radioGroup.check(R.id.radio_button2);
//                    } else {
//                        radioGroup.check(R.id.radio_button3);
//                    }
//                    EditText etReason = textEntryView.findViewById(R.id.reason);
//                    Object reason = item.getInventoryStatus();
//                    etReason.setText(String.valueOf(reason));
//                    new AlertDialog.Builder(getActivity()).setTitle("更新资产状态").setView(textEntryView).setIcon(R.drawable.warning_yellow)
//                            .setPositiveButton(getString(R.string.confirm), (dialogInterface, i12) -> {
//
//                                //更新数据库条目
//                                String s = ((RadioButton) textEntryView.findViewById(radioGroup.getCheckedRadioButtonId())).getText().toString();
//                                CommonUtil.toastShow(getActivity(), "reason:" + etReason.getText().toString() + ",status:" + s, CommonUtil.SUCCESS, true);
//                                String statusValue = getStatusValue(radioGroup);
//                                String reasonValue = etReason.getText().toString();
//                                ContentValues contentValues = new ContentValues();
//                                contentValues.put("InventoryStatus", statusValue);
//                                // contentValues.put("REASON", reasonValue);
//                                DatabaseUtil.updateData(DatabaseConstant.OFFLINE_INVENTORY_TASK_ITEM, contentValues, "FD_ID = ?", new String[]{fdId});
//
//                            })
//                            .setNeutralButton(getString(R.string.cancel), (dialogInterface, i1) -> dialogInterface.dismiss())
//                            .create().show();
//                    ;
//                }
//            }).create().show();
//            return true;
//        });

        scrollPageView = new ScrollPageView(getActivity());

        scrollPageView.setListView(listView);

        scrollPageView.setOnScrollPageListener(this::queryData);

        conditionSearchView = new ConditionSearchView(getActivity());
        dialog = new Dialog(getActivity());
        dialog.setContentView(conditionSearchView);
        conditionSearchView.setOnButtonClickListener(i -> {
            initStatus = true;
            initAdapterData();
            scrollPageView.setCurrentCount(0);
            queryData();
            dialog.dismiss();
        });
        dialog.create();

        // 获取对话框的窗口对象
        Window window = dialog.getWindow();
        if (window != null) {
            // 设置对话框在屏幕右上方
            window.setGravity(Gravity.TOP | Gravity.END);
            // 设置对话框宽度为屏幕宽度的90%
            WindowManager.LayoutParams layoutParams = window.getAttributes();
            layoutParams.width = (int) (getResources().getDisplayMetrics().widthPixels * 0.9);
            window.setAttributes(layoutParams);
        }
        dialog.setTitle("搜索条件");
        View tvMore = findViewById(R.id.tvMore);
        tvMore.setOnClickListener(view -> {

            dialog.show();
        });
        queryData();
//        queryConditionData();
        queryConditionDataNew();

        initQueryButton();
    }

    private void initAdapterData() {
        parentList.clear();
        runOnUiThread(() -> {
            listableAdapter.setAssetList(parentList);
        });
    }


    private String getStatusValue(RadioGroup v) {
        String s = ((RadioButton) v.findViewById(v.getCheckedRadioButtonId())).getText().toString();
        return getString(R.string.notCounted).equals(s) ? "0" : getString(R.string.counted).equals(s) ? "4" : "5";
    }

    private Activity getActivity() {
        return this;
    }

    private void setQueryStatus(int i) {
//        conditionSearchView.setSelectItem("status", 0);
        if (i == 0) {
            conditionSearchView.setSelectItem("status", 1);
        } else if (i == 4) {
            conditionSearchView.setSelectItem("status", 2);
        } else if (i == 5) {
            conditionSearchView.setSelectItem("status", 3);
        } else {
            conditionSearchView.setSelectItem("status", 0);
        }

        conditionSearchView.conditionValueHandle(false);


        initStatus = true;
        scrollPageView.setCurrentCount(0);
        initAdapterData();
        queryData();
    }

    /**
     * 查询搜索条件数据
     */
    private void queryConditionData() {
        String[] columnNames = {"notCountedCount", "countedCount", "errorCountedCount", "allCardCategoryName", "allDeptName", "allUseStatus"};
        Cursor countCursor = DatabaseUtil.rawQuery("SELECT " +
                "SUM(CASE WHEN inventoryStatus = '待盘点' THEN 1 ELSE 0 END) AS " + columnNames[0] + ", " +
                "SUM(CASE WHEN inventoryStatus =  '已盘点' THEN 1 ELSE 0 END) AS " + columnNames[1] + ", " +
                "SUM(CASE WHEN inventoryStatus =  '异常盘点' THEN 1 ELSE 0 END) AS " + columnNames[2] + ", " +
                "(\n" +
                "        SELECT GROUP_CONCAT(MeasurementUnit, ';')\n" +
                "        FROM (\n" +
                "            SELECT DISTINCT MeasurementUnit\n" +
                "            FROM OFFLINE_INVENTORY_TASK_ITEM\n" +
                "        )\n" +
                "    ) AS " + columnNames[3] + ", \n" +
                "(\n" +
                "        SELECT GROUP_CONCAT(UsingDepartment, ';')\n" +
                "        FROM (\n" +
                "            SELECT DISTINCT UsingDepartment\n" +
                "            FROM OFFLINE_INVENTORY_TASK_ITEM\n" +
                "        )\n" +
                "    ) AS  " + columnNames[4] + ", \n" +
                "    (\n" +
                "        SELECT GROUP_CONCAT(AssetUsageStatus, ';')\n" +
                "        FROM (\n" +
                "            SELECT DISTINCT AssetUsageStatus\n" +
                "            FROM OFFLINE_INVENTORY_TASK_ITEM\n" +
                "        )\n" +
                "    ) AS  " + columnNames[5] + " \n" +
                "FROM " + DatabaseConstant.OFFLINE_INVENTORY_TASK_ITEM, null);

        while (countCursor.moveToNext()) {
            for (String s : columnNames) {
                int columnIndex = countCursor.getColumnIndex(s);
                if (columnIndex >= 0) {

                    String value = countCursor.getString(columnIndex);
                    if ("".equals(value) || value == null) {
                        value = "0";
                    }

                    if ("notCountedCount".equals(s)) {
                        ((TextView) findViewById(R.id.notCountedCount)).setText(value);
                    }
                    if ("countedCount".equals(s)) {
                        ((TextView) findViewById(R.id.countedCount)).setText(value);
                    }
                    if ("errorCountedCount".equals(s)) {
                        ((TextView) findViewById(R.id.errorCountedCount)).setText(value);
                    }
                    if ("allCardCategoryName".equals(s)) {
                        conditionSearchView.setSelectValue("fdCardCategoryName", value);
                    }
                    if ("allDeptName".equals(s)) {
                        conditionSearchView.setSelectValue("fdDutyDeptName", value);
                    }
                    if ("allUseStatus".equals(s)) {
                        conditionSearchView.setSelectValue("useStatus", value);
                    }

                }
            }
        }
    }

    /**
     * 查询搜索条件数据(新）
     */
    private void queryConditionDataNew() {
        String[] columnNames = {"notCountedCount", "countedCount", "errorCountedCount", "allCardCategoryName", "allDeptName", "allUseStatus"};
        Cursor countCursor = DatabaseUtil.rawQuery("SELECT " +
                "SUM(CASE WHEN inventoryStatus = '待盘点' THEN 1 ELSE 0 END) AS " + columnNames[0] + ", " +
                "SUM(CASE WHEN inventoryStatus =  '已盘点' THEN 1 ELSE 0 END) AS " + columnNames[1] + ", " +
                "SUM(CASE WHEN inventoryStatus =  '异常盘点' THEN 1 ELSE 0 END) AS " + columnNames[2] + ", " +
                "(\n" +
                "        SELECT GROUP_CONCAT(unit, ';')\n" +
                "        FROM (\n" +
                "            SELECT DISTINCT unit\n" +
                "            FROM OFFLINE_INVENTORY_TASK_ITEM\n" +
                "        )\n" +
                "    ) AS " + columnNames[3] + ", \n" +
                "(\n" +
                "        SELECT GROUP_CONCAT(usingDepartment, ';')\n" +
                "        FROM (\n" +
                "            SELECT DISTINCT usingDepartment\n" +
                "            FROM OFFLINE_INVENTORY_TASK_ITEM\n" +
                "        )\n" +
                "    ) AS  " + columnNames[4] + ", \n" +
                "    (\n" +
                "        SELECT GROUP_CONCAT(usageStatus, ';')\n" +
                "        FROM (\n" +
                "            SELECT DISTINCT usageStatus\n" +
                "            FROM OFFLINE_INVENTORY_TASK_ITEM\n" +
                "        )\n" +
                "    ) AS  " + columnNames[5] + " \n" +
                "FROM " + DatabaseConstant.OFFLINE_INVENTORY_TASK_ITEM, null);

        while (countCursor.moveToNext()) {
            for (String s : columnNames) {
                int columnIndex = countCursor.getColumnIndex(s);
                if (columnIndex >= 0) {

                    String value = countCursor.getString(columnIndex);
                    if ("".equals(value) || value == null) {
                        value = "0";
                    }

                    if ("notCountedCount".equals(s)) {
                        ((TextView) findViewById(R.id.notCountedCount)).setText(value);
                    }
                    if ("countedCount".equals(s)) {
                        ((TextView) findViewById(R.id.countedCount)).setText(value);
                    }
                    if ("errorCountedCount".equals(s)) {
                        ((TextView) findViewById(R.id.errorCountedCount)).setText(value);
                    }
                    if ("allCardCategoryName".equals(s)) {
                        conditionSearchView.setSelectValue("fdCardCategoryName", value);
                    }
                    if ("allDeptName".equals(s)) {
                        conditionSearchView.setSelectValue("fdDutyDeptName", value);
                    }
                    if ("allUseStatus".equals(s)) {
                        conditionSearchView.setSelectValue("useStatus", value);
                    }

                }
            }
        }
    }

    private void queryData() {
        CommonUtil.openProgressDialog(getActivity(), getString(R.string.loading));

        String selection = conditionSearchView.getConditionClause();
        String[] selectionArgArray = conditionSearchView.getConditionArgs();

        if (initStatus) {
            int totalCursor = getTotalCount(selection, selectionArgArray);
            scrollPageView.setTotalCount(totalCursor);
            initStatus = false;
        }

        if (scrollPageView.getTotalCount() > 0) {
            //查询结果
            parentList.addAll(getAssetListDataNew(scrollPageView.getCurrentCount(), selection, selectionArgArray));
            runOnUiThread(() -> {
                listableAdapter.setAssetList(parentList);
                scrollPageView.setScrollListener(true);
                CommonUtil.cancelProgressDialog(getActivity());
            });
        } else {
            CommonUtil.cancelProgressDialog(getActivity());
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        scrollPageView.setCurrentCount(0);
        initStatus = true;
    }

    //返回主界面
    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
        }
        return super.onOptionsItemSelected(item);
    }

}
